<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate($type='host',$user='')
	{
		switch($type){
			case 'host':
				$user = new User('login');
				$res = $user->model()->find(array(
					'condition'=>'email=:email and user_type=:type',
					'params'=>array(
						':email'=>$this->username,
						':type'=>$type,
					),
				)); 
				if($res===null)
					$this->errorCode=self::ERROR_USERNAME_INVALID; // 用户名不存在
				else if(!$this->validatePassword($res->password))
					$this->errorCode=self::ERROR_PASSWORD_INVALID; //密码验证失败
				else
				{
					$this->_id=$res->user_id;
					$this->username=$res->user_name;
					$this->setState('avatar',$res->avatar);
					$this->setState('logintype','self');
					$this->setCookies($this->_id,$this->username);
					$this->errorCode=self::ERROR_NONE;
				}
				break;
			case 'renren':
				$this->_id = $user->user_id;
				$this->username = $user->user_name;
				$this->setState('avatar',$user->avatar);
				$this->setState('logintype','renren');
				$this->setCookies($this->_id,$this->username);
				$this->errorCode=self::ERROR_NONE;
				break;
		}
		return $this->errorCode==self::ERROR_NONE;
	}

	/**
	 * @return integer the ID of the user record
	 */
	public function getId()
	{
		return $this->_id;
	}

	protected function validatePassword($password){
		return ($password === $this->password);
	}
	public function bindRenren($user){
		
	}
	public function setCookies($uid,$username){
		setcookie('uid',$uid,10*3600,'/');	
		setcookie('username',$username,10*3600,'/');	
	}
}